﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CommonsLib.Utility;
using System.Data.SqlClient;
using MaxLeaf.Platform.Functions;
using System.Data.Common;
using MaxLeaf.Platform.Commons;
using MaxLeaf.Platform.DataContract;
using CommonsLib.DB;

namespace MaxLeaf.Platform.DALImplementation
{
    public class poOrderHdrDAL : BaseDAL
    {

        protected override string GetCondForPage(DBAccess dbcon, object model, List<Cond> lstCond)
        {
            string strCond = base.GetCondForPage(dbcon, model, lstCond);
            
            foreach (Cond cond in lstCond)
            {
                if (cond.PropName.Equals("Func_GetCompanyBill"))
                {
                    if (!string.IsNullOrEmpty(strCond))
                    {
                        strCond += " and ";
                    }
                    strCond += string.Format(@" ( 
                        (OrigCompanyID<>0  and OrigCompanyID={0}) 
                        or   ( CompanyID={0})
                        or exists(select a.CompanyID  from {1}mCompany  a where a.ParentId={0} and a.ParentId<>0  and a.CompanyID=case when poOrderHdr.OrigCompanyID<>0 then poOrderHdr.OrigCompanyID else poOrderHdr.CompanyID end) ) 
                    ", cond.Value,GetBaseDatabase());
                    continue;
                }
                
            }
            return strCond;
        }

        internal static string QryTableName(object model)
        {
            string strSql = @"(
            select h.*,isnull(d.TotAmt,0) as TotAmt from poOrderHdr h 
            left join (select HdrId,sum(Subtotal) as TotAmt  from poOrderDtl where is_delete=0 group by HdrId) d on h.finterid=d.HdrId
            ) poOrderHdr "
            ;

            return strSql;
        }
    }
}
